'use strict';

let model = require('../../model/mongo/user.js');
let debug = require('debug')('user');
let fout = require('../../common/function.js').formatOutput;
let md5 = require('../../common/function.js').md5;

function MongoDao() {
    let self = this instanceof MongoDao ? this : new MongoDao();
    return self;
}
module.exports = MongoDao;
let theProto = MongoDao.prototype;


theProto.save = function*(json) {
    let errCode = 0;
    let errMsg = null;
    let data = null;

    let item = new model({
        email: json.email,
        name: json.name,
        password: md5(json.password),
        role: json.role
    });

    try {
        let result = yield item.save();
        if (result.errors) {
            errMsg = result.errors;
        } else {
            data = result._doc;
        }
    } catch (e) {
        errMsg = e.toString();
    }

    if (errMsg) {
        errCode = 10101;
        errMsg = 'user: save error,' + errMsg;
    }

    return fout(errCode, errMsg, data);
};

theProto.check = function*(json) {
    let errCode = 0;
    let errMsg = null;
    let data = null;

    try {
        let result = yield model.findOne({
            email: json.email,
            password: md5(json.password)
        }, {
            password: 0
        });
        if (result && !result.errors && result._doc) {
            data = {matched: true};
        } else {
            errMsg = 'user: email password not match';
        }
    } catch (e) {
        errMsg = e.toString();
    }

    if (errMsg) {
        errCode = 10102;
        errMsg = 'user: check error,' + errMsg;
    }

    return fout(errCode, errMsg, data);
};